package com.cloudcc.mobile.view.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.text.TextUtils;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.bus.StartWebEvent;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.DialogUtils;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.view.web.NoScrollWebView;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.cloudcc.mobile.weight.webview.CloudccWebChromeClient;
import com.cloudcc.mobile.weight.webview.CloudccWebViewClient;
import com.cloudcc.mobile.widget.CloudCCTitleBar;
import com.litesuits.android.log.Log;

import static android.app.Activity.RESULT_OK;

/**
 * @author wangzhiqiang
 * @Description: webview基类
 * @date 2015-12-4 上午9:03:05 webview id必须 是 webview
 */
public class BaseWebViewFragment extends BaseFragment {

//    protected NoScrollWebView mWebView;
protected WebView mWebView;
    private WebSettings webSettings;

    protected CallLogLoadingDialog progressDialog;
    private boolean _isVisible;// 控制bindtoken影响的问题

    protected String mUrl = UrlManager.APP_UR;
    protected String mmUrl = UrlManager.APP_UR;

    protected String daoruurl = UrlManager.APP_UR;
    protected String cjlxrna;
    protected String cjlxrph;
    protected String form;
    protected WebViewClient mWebViewClient;
    protected WebChromeClient mWebChromeClient;

    protected boolean isRedirected;
    //导入联系人
    protected Button daoru_lian;
    protected CloudCCTitleBar headerbar;
    protected TextView et_mobile;
    protected LinearLayout daoru_lay;
    protected String username, usernumber;
    protected ImageView daoru_lian_im;
    private Cursor phone, cursor;

    @Override
    public void init() {
        super.init();
        mWebView = (WebView) findViewById(R.id.webview);
        daoru_lian = (Button) findViewById(R.id.daoru_lian);
        headerbar = (CloudCCTitleBar) findViewById(R.id.headerbar);
        et_mobile = (TextView) findViewById(R.id.et_mobile);
        daoru_lay = (LinearLayout) findViewById(R.id.daoru_lay);
        daoru_lian_im = (ImageView) findViewById(R.id.daoru_lian_im);
        onPreInitWebView();
        initSetting();
        initClient();
        initWebView();
    }


    /**
     * 在初始化webview之前调用
     */
    protected void onPreInitWebView() {

    }

    @SuppressLint({"JavascriptInterface", "SetJavaScriptEnabled"})
    protected void initSetting() {
        webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
//		mWebView.addJavascriptInterface(new JSObject(mWebView), "JsInterface");
//		((WebView) webSettings).addJavascriptInterface(,
//	                "android");
        webSettings.setAllowFileAccess(true);
        webSettings.setBlockNetworkImage(false);// 后来加的
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);// 是否缓存
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(false);// 不显示 放大图标
    }

    ValueCallback<Uri> mUploadMessage;
    ValueCallback<Uri[]> mUploadCallbackAboveL;
    /**
     * 初始化 客户端
     */
    protected int loadProgress = 0;
    private final int OPEN_RESULT = 1;
    private final int PINK_RESULT = 2;
    private final int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 3;

    protected void initClient() {
        mWebView.addJavascriptInterface(new JsInteration(), "cloudcc");
        mWebView.setWebViewClient(getWebViewClient());
        mWebView.setWebChromeClient(new CloudccWebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                loadProgress = newProgress;
                super.onProgressChanged(view, newProgress);
                if (loadProgress == 100) {
                    stopProgressDialog();
                } else {
                    startProgressDialog();
                }
            }

            // For Android 5.0+
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(
                        Intent.createChooser(i, "File Browser"),
                        FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
                return true;
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                        String acceptType) {
                if (mUploadMessage != null)
                    return;
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "选择文件"),
                        PINK_RESULT);
            }

            // For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadFile,
                                        String acceptType, String capture) {
                openFileChooser(uploadFile, acceptType);
            }

            // For Android 3.0-
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooser(uploadMsg, "");
            }
        });
        mWebView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String arg0, String arg1, String arg2,
                                        String arg3, long arg4) {
                // TODO Auto-generated method stub
                Log.d("webview", "zoule");
                Uri uri = Uri.parse(arg0);
                Intent it = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(it);
                stopProgressDialog();
            }
        });
    }

    private String mxUrl;
    private String mxxUrl;

    @SuppressLint("SdCardPath")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == PINK_RESULT) {
                if (null == mUploadMessage)
                    return;
                Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;

            } else if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
                if (null == mUploadCallbackAboveL)
                    return;
                Uri result = (intent == null || resultCode != RESULT_OK) ? null : intent.getData();
                if (result != null) {
                    mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
                } else {
                    mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
                }
                mUploadCallbackAboveL = null;
            }
        }
    }

    /**
     * 初始化
     */
    public void initWebView() {
        load();
    }

    public void load() {
        if (mUrl.contains("obj=003")) {
            if (!TextUtils.isEmpty(cjlxrph) || !TextUtils.isEmpty(cjlxrna)) {
                mUrl = mUrl + "&name=" + cjlxrna + "&shouji=" + cjlxrph;
            }

        }

        mWebView.loadUrl(mUrl);

        mWebView.reload();
    }


    /**
     * 设置出事url
     *
     * @return
     */
    protected String getUrl() {
        return mUrl;
    }

    protected void setUrl(String url) {
        mUrl = url;
    }

    /**
     * dialog开始显示
     */
    protected void startProgressDialog() {
        if (_isVisible) {
            if (progressDialog == null) {
                progressDialog = new CallLogLoadingDialog(getActivity(),R.style.DialogLoadingTheme);
                progressDialog.setCancelable(true);
                progressDialog.setCanceledOnTouchOutside(false);
                progressDialog.show();
                progressDialog.settext(getString(R.string.loading));
            }
            if (!progressDialog.isShowing()) {
                try {
                    progressDialog.show();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }

            }
        }
    }

    /**
     * 停止dialog
     */
    protected void stopProgressDialog() {
        if (_isVisible && progressDialog != null) {
            try {
                progressDialog.dismiss();
                progressDialog = null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public void onResume() {
        _isVisible = true;
        super.onResume();
    }

    @Override
    public void onPause() {
        _isVisible = false;
        super.onPause();
    }

    @Override
    public int getLayoutId() {
        return R.layout.widget_webview;
    }

    protected class BaseWebViewClient extends CloudccWebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            LogUtils.d("webview", "开始加载url:" + url);
            if (url.contains("selectedRecordType")) {
//				if(!url.contains("&name")) {
                mmUrl = url;
//				}

            }
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            LogUtils.d("webview", "开始完成url:" + url);

            super.onPageFinished(view, url);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogUtils.d("webview", "跳转url:" + url);
            if (UrlManager.isWapLogin(url)) {// 登录
                onLoginInvalid(view, url);
                return true;
            }
            if (UrlManager.isHome(url)) {// 主页
                getActivity().finish();
                return true;
            }
            if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:") || url.startsWith("smsto:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

    }

    /**
     * 失效的时候
     *
     * @param view
     * @param url
     */
    public void onLoginInvalid(WebView view, String url) {
        EventEngine.register(this);
        Intent intent = new Intent(mContext, BindActivity.class);
        startActivity(intent);
    }

    /**
     * 重新bin定的时候
     *
     * @param event
     */
    public void onEventMainThread(StartWebEvent event) {
        if (event.isError()) {
            EventEngine.post(new MenuToggleEvent(false, false));
            getActivity().finish();
            return;
        }
        mWebView.loadUrl(mUrl);
        EventEngine.uregister(this);
    }

    public class JsInteration {

        @JavascriptInterface
        public void back() {
            ((Activity) mContext).finish();

        }

        @JavascriptInterface
        public void home() {
            DialogUtils.Exit(mContext);
        }

        @JavascriptInterface
        public void refresh() {
            mWebView.reload();
        }
    }

    public WebViewClient getWebViewClient() {
        return new BaseWebViewClient();
    }

}
